package com.yhy.common.mybatis.handler;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import org.apache.ibatis.reflection.MetaObject;

import java.time.LocalDateTime;

/**
 * 自定义公共字段填充处理器
 */
public class MyMetaObjectHandler implements MetaObjectHandler {

    /**
     * 逻辑删除否 0-未删除,1-已删除
     */
    private static final Boolean TABLE_LOGIC_FALSE = Boolean.FALSE;

    /**
     * 插入操作自动填充
     */
    @Override
    public void insertFill(MetaObject metaObject) {
        Object createTime = getFieldValByName("createTime", metaObject);
        Object deleted = getFieldValByName("isDeleted", metaObject);
        LocalDateTime currentDate = LocalDateTime.now();
        if (createTime == null) {
            setFieldValByName("createTime", currentDate, metaObject);
        }
        if (deleted == null) {
            setFieldValByName("isDeleted", TABLE_LOGIC_FALSE, metaObject);
        }
    }

    /**
     * 修改操作自动填充
     */
    @Override
    public void updateFill(MetaObject metaObject) {
        Object updateTime = getFieldValByName("updateTime", metaObject);
        LocalDateTime currentDate = LocalDateTime.now();
        if (updateTime == null) {
            setFieldValByName("updateTime", currentDate, metaObject);
        }
    }

}
